Go Details & Tips 101 (20230202) by Tapir Liu
Author:Tapir Liu
Language: eng
Format: epub
The famous := trap
Let's view a simple program.
package main import "fmt" import "strconv" func parseInt(s string) (int, error) { n, err := strconv.Atoi(s) if err != nil { fmt.Println("err:", err) b, err := strconv.ParseBool(s) if err != nil { return 0, err } fmt.Println("err:", err) if b { n = 123 } } return n, err } func main() { fmt.Println(parseInt("true")) }
We know that the call strconv.Atoi(s) will return a non-nil error, but the call strconv.ParseBool(s) will return a nil error. Then, will the call parseInt("true") return a nil error, too? The answer is it will return a non-nil error. The outputs of the program is shown below:
err: strconv.Atoi: parsing "true": invalid syntax err: <nil> 123 strconv.Atoi: parsing "true": invalid syntax
Wait, isn't the err variable is re-declared in the inner code block and its value has been modified to nil before the parseInt("true") returns? This is a confusion many new Go programmers, including me, ever encountered when they just started using Go.
The reason why the call parseInt("true") returns a non-nil error is a variable declared in an inner code block is never a re-declaration of a variable declared in an outer code block. Here, the inner declared err variable is set (initialized) as nil. It is not a re-declaration (a.k.a. modification) of the outer declared err variable. The outer one is set (initialized) as a non-nil value, then it is never changed later.
There is the voice to remove the ... := ... re-declaration syntax form from Go. But it looks this is a too big change for Go. Personally, I think explicitly marking the re-declared variables out is a more feasible solution.
Download
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
The Art of Coaching Workbook by Elena Aguilar(51098)
Trainspotting by Irvine Welsh(21585)
The Secret History by Donna Tartt(18971)
Twilight of the Idols With the Antichrist and Ecce Homo by Friedrich Nietzsche(18586)
All the Missing Girls by Megan Miranda(15812)
Cat's cradle by Kurt Vonnegut(15276)
Ready Player One by Cline Ernest(14593)
Talking to Strangers by Malcolm Gladwell(13318)
Fangirl by Rainbow Rowell(9193)
The remains of the day by Kazuo Ishiguro(8906)
The Compound Effect by Darren Hardy(8887)
Thirteen Reasons Why by Jay Asher(8856)
Tools of Titans by Timothy Ferriss(8324)
Periodization Training for Sports by Tudor Bompa(8227)
Wonder by R. J. Palacio(8070)
The Lover by Duras Marguerite(7863)
A Court of Wings and Ruin by Sarah J. Maas(7757)
Change Your Questions, Change Your Life by Marilee Adams(7697)
The Complete Stick Figure Physics Tutorials by Allen Sarah(7344)